<script setup lang="ts">
import { useGuessLIst } from '@/composables'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import CategoryPanel from './components/CategoryPanel.vue'
import CustomNavbar from './components/CustomNavbar.vue'
import HotPanel from './components/HotPanel.vue'
import pageSkeleton from './components/pageSkeleton.vue'
// --------------轮播图数据--------------
// 定义轮播图数据
const banners = ref<BannerItem[]>([])

// 获取轮播图数据
const getBannerData = async () => {
  const res = await getHomeBannerAPI()
  banners.value = res.result
  console.log('banner', banners.value)
}
// 调用获取数据的方法
getBannerData()
// --------------前台类目数据--------------
// 定义前台类目数据
const categoryList = ref<CategoryItem[]>([])

// 获取前台类目数据
const getCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}
// 调用获取数据的方法
getCategoryData()
// --------------热门推荐数据--------------
// 定义热门推荐数据
const hotList = ref<HotItem[]>([])

// 获取热门推荐数据
const getHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}
// 调用获取数据的方法
getHotData()
// --------------猜你喜欢数据--------------
// // 获取猜你喜欢数据实例
// const guessRef = ref<XtxGuessInstance>()

// // --------------滚动到底部/右边，会触发 scrolltolower 事件--------------
// // 滚动到底部/右边，会触发 scrolltolower 事件
// const handleScrollToLower = () => {
//   console.log('滚动到底部')
//   // 获取更多数据
//   guessRef.value?.getMore()
// }
const { guessRef, onScrolltolower: handleScrollToLower } = useGuessLIst()
// --------------下拉刷新--------------
// 下拉刷新被触发
const isRefreshing = ref(false)
// 自定义下拉刷新被触发
const handleRefresh = async () => {
  console.log('下拉刷新')
  // 下拉刷新开始
  isRefreshing.value = true
  // 重置猜你喜欢组件数据
  guessRef.value?.resetData() // 加载数据
  // 获取数据
  await Promise.all([getBannerData(), getCategoryData(), getHotData(), guessRef.value?.getMore()])
  // 下拉刷新结束
  isRefreshing.value = false
}

const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getBannerData(), getCategoryData(), getHotData()])
  isLoading.value = false
})
</script>

<template>
  <!-- 自定义导航条 -->
  <CustomNavbar></CustomNavbar>
  <scroll-view
    scroll-y
    class="scroll-view"
    refresher-enabled
    @scrolltolower="handleScrollToLower"
    :refresher-triggered="isRefreshing"
    @refresherrefresh="handleRefresh"
  >
    <pageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="banners" />
      <!-- 前台类目 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
